package com.mathlearning.auth.util;

import com.mathlearning.auth.config.WeChatConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class WeChatUtil {

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取微信授权URL
     * 
     * @param state 状态参数，用于防止CSRF攻击
     * @return 授权URL
     */
    public String getAuthUrl(String state) {
        String appId = weChatConfig.getAppId();
        String redirectUri = java.net.URLEncoder.encode(
            weChatConfig.getRedirectUri(), 
            java.nio.charset.StandardCharsets.UTF_8
        );
        
        return String.format(
            "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect",
            appId,
            redirectUri,
            state
        );
    }

    /**
     * 通过code换取access_token
     */
    public Map<String, Object> getAccessToken(String code) {
        String appId = weChatConfig.getAppId();
        String appSecret = weChatConfig.getAppSecret();
        
        String url = String.format(
            "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
            appId,
            appSecret,
            code
        );
        
        return restTemplate.getForObject(url, HashMap.class);
    }

    /**
     * 获取微信用户信息
     */
    public Map<String, Object> getUserInfo(String accessToken, String openid) {
        String url = String.format(
            "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",
            accessToken,
            openid
        );
        
        return restTemplate.getForObject(url, HashMap.class);
    }
}










